package com.baiyi.homeui.hshomeui.util;
import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class JsonUtils {

    public static Gson mGson = new Gson();
    private JsonUtils() {}




    /**
     * 将json字符串转化成实体对象
     */
    public static <T> T stringToObject(String json , Class<T> classOfT){
        try {
            return  mGson.fromJson(json , classOfT ) ;
        }catch (Exception e){
            Log.e("jsonUtil","Exception---stringToObject--fail--"+e.getMessage());
            return  null;
        }

    }

    /**
     * 将对象准换为json字符串 或者 把list 转化成json
     */
    public static <T> String objectToString(T object) {
        return mGson.toJson(object);
    }

    /**
     * 把json 字符串转化成list
     */
    public static <T> List<T> stringToList(String json , Class<T> cls  ){
        if(TextUtils.isEmpty(json)) {
            return new ArrayList<>();
        }
        List<T> list = new ArrayList<>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for(final JsonElement elem : array){
            list.add(mGson.fromJson(elem, cls));
        }
        return list ;
    }

    /**
     * 将Map拼接转化为标准json字符串
     */
    public static <T> String mapToJson(Map<String, T> map) {
        return mGson.toJson(map);
    }

    public static String getJsonFromFile(String fileName,Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

}
